package communication.listeners;

import server.Server;
import server.ServerCommunicator;
import message.Message;
import message.ServerMessageWrapper;
import message.ShutDownServerRequestMessage;
import message.ShutDownServerResponseMessage;
import communication.MessageListener;
import communication.MessageReceivedEvent;

public class ShutDownListener implements MessageListener
{
	private final Server server;
	private final ServerCommunicator communicator;
	
	public ShutDownListener(ServerCommunicator communicator, Server server)
	{
		this.communicator = communicator;
		this.server = server;
	}
	
	@Override
	public void messageRecieved(MessageReceivedEvent e)
	{
		ServerMessageWrapper message = ((ServerMessageWrapper) e.getMessage());
		ShutDownServerResponseMessage response = new ShutDownServerResponseMessage();
		
		response.setShuttingDown(true);
		
		server.stop();
		
		communicator.sendMessage(message.connectionId, response);
	}

	@Override
	public boolean acceptsMessage(Message message)
	{
		if (message.getClass().equals(ServerMessageWrapper.class))
			message = ((ServerMessageWrapper) message).internalMessage;
		
		return message.getClass().equals(ShutDownServerRequestMessage.class);
	}

}
